//
//  bookmarkView.swift
//  YoruNeko
//  根书签视图，显示根目录，并创建子目录
//  Created by  mahoPunch on 2021/6/15.
//

import SwiftUI

struct BookmarkView: View {
    
    //书签根视图保有一个YRNKBookmark数组拷贝，进行增删操作时拷贝与储存执行相同操作,实现UI与储存同步
    //展示使用数组，删除增添如何处理？如何确定当前层次结构？
    @StateObject var modelData: BookmarkModelData =
        .init(with: (try? BookmarkManager.getCachedBookmarkRoot()) ?? YRNKBookmark.init())
    
    @State var selectedList = Set.init([YRNKBookmark].init())
    @State var onRefresh: Bool = false
    
    var callback: BookmarkCallBack?
    
    var currentBookmarks:[YRNKBookmark]{
        get{
            modelData.curBookmarkFolder.children!
        }
        set{
            
        }
    }

    var currentFilteredBookmark:[YRNKBookmark]{
        modelData.curBookmarkFolder.children!.filter({ yrnkBookmark in
            if let url = yrnkBookmark.this.url {
                return searchKeyword.isEmpty || yrnkBookmark.this.name.containsIgnoringCase(find: searchKeyword) || url.containsIgnoringCase(find: searchKeyword)
            }
            else {
                return searchKeyword.isEmpty || yrnkBookmark.this.name.containsIgnoringCase(find: searchKeyword)
            }
        })
    }
    
    var bookmark_subtitle: String{
        if isSelectMode{
            return "-已选\(selectedList.count)项"
        }
        else{
            return ""
        }
    }
    
    //控制弹出Editor的状态量
    @State private var showNewBookmarkEditor: Bool = false
    @State private var showEditBookmarkEditor: Bool = false
    
    //编辑和新增共用的Name和Url
    @State private var editBookmarkName: String = ""
    @State private var editBookmarkUrl: String = ""
    @State private var IDOfEditBookmark: UUID = UUID()
    @State private var isDirectory: Bool = false
    
    //移动书签模式
    @State private var isMoveMode: Bool = false
    @State private var bookmarkMoveCache: YRNKBookmark = YRNKBookmark()

    
    //搜索框相关状态量
    @State private var searchKeyword: String = ""
    @State private var isEditing: Bool = false;
    //多选模式
    @State private var isSelectMode: Bool = false
    
    //移动模式
    
    //弹出书签编辑框
    func activeEditBookmarkAlert(_ bookmark: Bookmark) -> Void {
        editBookmarkName = bookmark.name
        if let url = bookmark.url {
            editBookmarkUrl = url
        }
        IDOfEditBookmark = bookmark.id
        isDirectory = (bookmark.url == nil)
        showEditBookmarkEditor = true
    }
    //弹出新书签编辑框
    func activeNewBookmarkAlert() -> Void {
        showNewBookmarkEditor = true
    }
    
    func deleteBookmark(_ bookmarkID: UUID) -> Void{
        callback?.deleteBookmark(to: bookmarkID)
        modelData.curBookmarkFolder.children! = modelData.curBookmarkFolder.children!.filter({$0.this.id != bookmarkID})
        modelData.objectWillChange.send()
    }
    
    
    func accessBookmarkFolder(_ bookmarkID: UUID) -> Void{
       // let parent = modelData.curBookmarkFolder
        modelData.curBookmarkFolder = modelData.curBookmarkFolder.children![modelData.curBookmarkFolder.children!.firstIndex(where: {
            $0.this.id == bookmarkID})!]
        //modelData.curBookmarkFolder.editParent(parent: parent)
    }
    
    func accessBookmark(_ bookmarkID: UUID) -> Void{
        callback?.goToView(to: .IndexView, from: .BookmarkView, intent: .Default, with: [.url: BookmarkManager.findItemByUuid(uuid: bookmarkID)?.this.url as Any])
    }

    func backUpperFolder(){
        if modelData.curBookmarkFolder.parent != nil {
            modelData.curBookmarkFolder = modelData.curBookmarkFolder.parent!
            modelData.objectWillChange.send()
        }
    }
    
    func onMoveDone(){
        if bookmarkMoveCache.parent! !==
            modelData.curBookmarkFolder{
            //持久层
            callback?.deleteBookmark(to: bookmarkMoveCache.this.id)
            callback?.addBookmark(bookmarkMoveCache, to: modelData.curBookmarkFolder.this.id)
            //视图层
            bookmarkMoveCache.parent!.deleteChild(childId: bookmarkMoveCache.this.id)
            modelData.curBookmarkFolder.addChild(child: bookmarkMoveCache)
        }
    }
    
    var body: some View {
        //需要保留对子数组的引用
        
        NavigationView{
            VStack {//占位用
                BookmarkSearchTab(searchKeyword: $searchKeyword, isEditing: $isEditing).padding(.vertical, 5)
                if (isMoveMode && modelData.curBookmarkFolder.parent != nil){
                    HStack{
                        Image(systemName: "arrowshape.turn.up.backward.circle")
                            .resizable()
                            .frame(width: 30, height: 30, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/)
                            .foregroundColor(Color(.systemGray))
                        
                        Text("上级文件夹")
                        Spacer()
                    }
                    .onTapGesture(perform: {
                        //返回上级文件夹
                        backUpperFolder()
                        
                    })
                    .padding(.leading, 5)
                }
                BookmarkList(bookmarks: currentFilteredBookmark, isSelectMode: $isSelectMode, isMoveMode: $isMoveMode, bookmarkCache: $bookmarkMoveCache, selectedList: $selectedList, onSummonEditAlert: {
                    bookmarkToBeEdit in
                    activeEditBookmarkAlert(bookmarkToBeEdit)
                }, onBookmarkDelete: {
                    IDOfbookmarkToBeDelete in
                    deleteBookmark(IDOfbookmarkToBeDelete)
                }, onFolderClick: {
                    IDOfBookmarkFolderToBeAccess in
                    accessBookmarkFolder(IDOfBookmarkFolderToBeAccess)
                }, onBookmarkClick: {
                    IDOfBookmarkToBeAccess in
                    //callback?.goToView(by: .IndexView, sender: self, with: [RequestArgumentKey.id.rawValue:IDOfBookmarkToBeAccess])
                    accessBookmark(IDOfBookmarkToBeAccess)
                    
                }
                )

                    
            }/*VStack*/
            .padding(.top, 5)
            .navigationTitle(isMoveMode ? "移动到\(modelData.curBookmarkFolder.this.name)" : (isSelectMode ? "\(modelData.curBookmarkFolder.this.name)\(bookmark_subtitle)" : (modelData.curBookmarkFolder.parent == nil ? "书签" : modelData.curBookmarkFolder.this.name)))
            .navigationBarItems(leading:
                Button {
                    //onBackButtonPresse()
                    if isMoveMode{
                        isMoveMode = false
                    }
                    else if isSelectMode{
                        isSelectMode = false
                    }
                    else{
                        if modelData.curBookmarkFolder.parent != nil {
                            modelData.curBookmarkFolder = modelData.curBookmarkFolder.parent!
                            modelData.objectWillChange.send()
                        }
                        else {
                            callback?.goBack()
                        }
                    }
                    
                } label: {
                    HStack {
                        
                        if (isSelectMode || isMoveMode){
                            Text("取消")
                        }
                        else{
                            Image(systemName: "chevron.backward")
                            Text("返回")
                        }
                        
                    }
                },trailing:
                    HStack {
                        
                        Button(action: {
                            isMoveMode = false
                            //移动至当前目录
                            onMoveDone()
                            
                        }){
                            if isMoveMode{
                                Text("完成")
                            }
                            
                        }
                        
                        
                        Menu(content: {
                            if isSelectMode {//选择状态
                                Button(action: {
                                    isSelectMode = false
                                    callback?.deleteBookmarks(to: selectedList.compactMap({
                                        return $0.this.id
                                    }))
                                    
                                    
                                    modelData.curBookmarkFolder.children! = modelData.curBookmarkFolder.children!.filter({
                                        !selectedList.contains($0)
                                    })
                                }){
                                    Image(systemName: "trash")
                                    Text("删除")
                                }
                                .foregroundColor(.red)
                            }
                            else {//非选择状态为新增
                                Button(action: {
                                    activeNewBookmarkAlert()
                                }){
                                    Image(systemName: "plus.circle")
                                        .foregroundColor(Color(.systemBlue))
                                    Text(isMoveMode ? "新建文件夹" : "新建书签")
                                }
                                
                            }

                        }){
                            if isSelectMode {
                                Image(systemName: "ellipsis")
                            }
                            else {
                                Image(systemName: "plus")
                            }
                            
                        }
                        
                    }
            )
        .navigationBarTitleDisplayMode(.inline)

        }
        .overlay(//唤醒新建书签的编辑框
            NewBookmarkEditorAlert(isPresent:$showNewBookmarkEditor, isMoveMode: $isMoveMode, onEditDone: {
                bookmark in
                /* 需要增加对持久化数据的操作 */
                
                let child = YRNKBookmark(reference: bookmark, parent: modelData.curBookmarkFolder, isDirectory: isMoveMode)
                callback?.addBookmark(child, to: modelData.curBookmarkFolder.this.id)
                //modelData.curBookmarkFolder.addChild(child: child)
                modelData.objectWillChange.send()
            })
                )
        .overlay(//唤醒编辑书签的编辑框
            EditBookmarkEditorAlert(isPresent: $showEditBookmarkEditor, isDirectory: $isDirectory, siteNameText: $editBookmarkName, url: $editBookmarkUrl, onEditDone: {
                /* 需要增加对持久化数据的操作 */
                modelData.curBookmarkFolder.children![modelData.curBookmarkFolder.children!.firstIndex(where: {$0.this.id == IDOfEditBookmark})!].editBookmark(withName: editBookmarkName, andURL: editBookmarkUrl)
                modelData.objectWillChange.send()
            })
                )
        
    }/*body*/
}/*BookmarkView*/
    

struct bookmarkView_Previews: PreviewProvider {
    static var previews: some View {
        BookmarkView()
            //.environmentObject(BookmarkModelData())
    }
}
